package com.study.zzedu.ui.login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.zhouwei.library.CustomPopWindow;
import com.study.zzedu.R;
import com.study.zzedu.base.BaseMvpActivity;
import com.study.zzedu.entity.Chapter;
import com.study.zzedu.ui.forgetpwd.ForgetPwdActivity;
import com.study.zzedu.ui.graduateservice.GraduatesServiceActivity;
import com.study.zzedu.ui.home.HomeActivity;
import com.study.zzedu.ui.tuitioninfo.TuitionInfoActivity;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.OkHttpUtils;
import com.study.zzedu.utils.SharedPreferencesHelper;
import com.study.zzedu.utils.ToastUtil;
import com.study.zzedu.utils.Utils;
import com.study.zzedu.widget.InfoDialog;
import com.study.zzedu.widget.LoadingDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.UUID;

public class LoginActivity extends BaseMvpActivity<LoginContract.IView, LoginPresenter> implements LoginContract.IView, View.OnClickListener {
    private TextView username, password,btnForget;
    private Button login;
    //public Boolean autoLoginFlag;//true:手动登录  false：自动登录
    private String deviceId = "";

    private EditText et_code;
    private ImageView iv_code;
    private String codeUUID = "",theToken = "";
    private boolean isshowpwd = true;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_login;
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected LoginContract.IView createView() {
        return this;
    }

    @Override
    protected void initView() {
        //autoLoginFlag = false;
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        btnForget = findViewById(R.id.btn_forget);
        rl_eye = (RelativeLayout)findViewById(R.id.rl_eye);
        et_code = findViewById(R.id.et_code);
        iv_code = findViewById(R.id.iv_code);

        login = findViewById(R.id.login);
    }
    RelativeLayout rl_eye;
    @Override
    protected void initData() {
        deviceId = (SharedPreferencesHelper.getInstance(this).getStringKey("deviceid"));
        if(TextUtils.isEmpty(deviceId)){
            deviceId = UUID.randomUUID().toString();
            SharedPreferencesHelper.getInstance(LoginActivity.this).put("deviceid", deviceId);
        }
        switchView();

        String name = SharedPreferencesHelper.getInstance(this).getStringKey("loginName");
        String pwd = SharedPreferencesHelper.getInstance(this).getStringKey("loginPwd");
        if("".endsWith(name) || "".endsWith(pwd)){
            return;
        }else {
            username.setText(name);
            password.setText(pwd);

        }
        //获取本地偏好数据，自动登录
        if(AppConstant.AUTO_LOGIN.equals((SharedPreferencesHelper.getInstance(this).getStringKey("loginState")))){//代表免登陆--->自动登录
            autoProgress(true);
            getPresenter().getAutoLoginToken(LoginActivity.this);
        }else {
            //ToastUtil.showShortToast("非自动登录");
        }
    }

    @Override
    protected void initListener() {
        rl_eye.setOnClickListener(this);
        btnForget.setOnClickListener(this);
        login.setOnClickListener(this);
        iv_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                autoProgress(true);
                getPresenter().getImageCode(LoginActivity.this);
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        getPresenter().getImageCode(LoginActivity.this);
    }

    @Override
    public void getData(String data) {}

    @Override
    public void showError(String error) {
        getPresenter().getImageCode(LoginActivity.this);
        autoProgress(false);
        if (null != error && !TextUtils.isEmpty(error)) {
            ToastUtil.showShortToast(error);
//            InfoDialog ifd = new InfoDialog.Builder(LoginActivity.this).create();
//            ifd.show();
        }
    }
    private void switchView(){
        if (!isshowpwd) {
            isshowpwd = true; password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            //否则隐藏密码
            isshowpwd = false; password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_eye:
                switchView();
                break;
            case R.id.btn_forget:
                Intent intent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                startActivity(intent);
                break;
            case R.id.login:
                if(TextUtils.isEmpty(et_code.getText().toString()))
                {
                    ToastUtil.showShortToast("验证码不能为空");
                    return;
                }
                loginAction();
                break;
        }
    }

    private void loginAction(){
        String usernameStr = username.getText().toString().trim();
        String passwordStr = password.getText().toString().trim();
        if(TextUtils.isEmpty(usernameStr) || TextUtils.isEmpty(passwordStr)){
            ToastUtil.showShortToast("输入不能为空");
            return;
        }
        if(TextUtils.isEmpty(deviceId)){
            ToastUtil.showShortToast("deviceid异常");
            return;
        }
        autoProgress(true);
        getPresenter().getLoginToken(LoginActivity.this);
    }
    @Override
    public void onCodeReturn(String data) {
        try {
            autoProgress(false);
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");
            if(jArray == null)
                return;
            if(jArray.length() == 0)
                return;

            String d = jArray.getJSONObject(0).getString("img");

            iv_code.setBackground(new BitmapDrawable(Utils.stringToBitmap(d)));
            codeUUID = jArray.getJSONObject(0).getString("uuid");
        }catch (Exception e){
            e.toString();
        }
    }

    @Override
    public void onLoginReturn(String data) {
        if (data != null) {
            try {
                autoProgress(false);
                ToastUtil.showShortToast("登录成功");
                //记录登录成功状态及登录数据
                {
                    //设置自动登录标志
                    SharedPreferencesHelper.getInstance(LoginActivity.this).put("loginState", AppConstant.AUTO_LOGIN);
                    SharedPreferencesHelper.getInstance(LoginActivity.this).put("loginName",username.getText().toString());
                    SharedPreferencesHelper.getInstance(LoginActivity.this).put("loginPwd",password.getText().toString());
                }
                JSONObject jObject = new JSONObject(data);
                JSONArray jArray = jObject.getJSONArray("data");
                if(jArray != null && jArray.length()>0){
                    String pwdStatus = jArray.getJSONObject(0).getString("pwdStatus");
                    if("异常".equals(pwdStatus)){
                        ToastUtil.showLongToast("初始密码，请修改密码");
                    }

                    String status = jArray.getJSONObject(0).getString("status");
                    if("未缴费".equals(status)){
                        Intent intent = new Intent(LoginActivity.this, TuitionInfoActivity.class);
                        startActivity(intent);
                    }else if("已毕业".equals(status)){
                        Intent intent = new Intent(LoginActivity.this, GraduatesServiceActivity.class);
                        startActivity(intent);
                        finish();
                    }else if("正常".equals(status)){
                        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    }else if("未复核".equals(status)){
                        ToastUtil.showLongToast("请登录电脑端进行复核");
                    }else {
//                        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//                        startActivity(intent);
//                        finish();
                        ToastUtil.showLongToast(""+status);
                    }
                }
            }catch (Exception e){
                ToastUtil.showShortToast(e.toString());
            }
        }
    }

    @Override
    public void onImageCodeError(String error) {
        autoProgress(false);
        if (null != error && !TextUtils.isEmpty(error)) {
            ToastUtil.showShortToast(error);
        }
    }


    @Override
    public void onTokenReturn(String data) {
        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");
            if(jArray == null)
                return;
            if(jArray.length() == 0)
                return;

            theToken = jArray.get(0).toString();

            //autoLoginFlag = true;
            String usernameStr = username.getText().toString().trim();
            String passwordStr = password.getText().toString().trim();
            LogUtil.e("Forget","password:"+passwordStr);
            String tokenPsd = Utils.digest(Utils.digest(passwordStr)+theToken);
            getPresenter().login(LoginActivity.this,usernameStr,tokenPsd ,et_code.getText().toString(),codeUUID,Utils.digest(deviceId));
        }catch (Exception e){
            e.toString();
        }
    }
    @Override
    public void onAutoTokenReturn(String data) {
        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");
            if(jArray == null)
                return;
            if(jArray.length() == 0)
                return;
            theToken = jArray.get(0).toString();

            String usernameStr = username.getText().toString().trim();
            String passwordStr = password.getText().toString().trim();
            //LogUtil.e("Forget","password:"+passwordStr);
            String tokenPsd = Utils.digest(Utils.digest(passwordStr)+theToken);
            getPresenter().autoLogin(LoginActivity.this,usernameStr,tokenPsd,Utils.digest(deviceId));
        }catch (Exception e){
            e.toString();
        }
    }

    private LoadingDialog mDialog;
    private void autoProgress(boolean show){
        if(mDialog==null){
            mDialog = new LoadingDialog(LoginActivity.this);
            //mDialog.setMessage("正在加载数据。。。");
        }
        if(show){
            mDialog.show();
        }else{
            mDialog.dismiss();
        }
    }
}
